/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.msg.hrappy.web.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.msg.hrappy.backend.model.DepartmentType;
import edu.msg.hrappy.backend.model.Job;
import edu.msg.hrappy.backend.model.Notification;
import edu.msg.hrappy.backend.model.User;
import edu.msg.hrappy.backend.service.DepartmentTypeService;
import edu.msg.hrappy.backend.service.JobService;
import edu.msg.hrappy.backend.service.UserService;
import edu.msg.hrappy.backend.service.exception.ServiceException;
import edu.msg.hrappy.backend.service.util.Validator;

/**
 *
 * @author toroke
 */
public class UpdateJobServlet extends HttpServlet {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@EJB
    private JobService jobService;
    @EJB
    private DepartmentTypeService depService;
    @EJB 
    private UserService userService;

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        HttpSession session = req.getSession();
        
        session.setAttribute("er", null);
        session.setAttribute("requirementsMessage", "");
		session.setAttribute("nameMessage", "");
		session.setAttribute("responsibilitiesMessage", "");
        Long id = Long.parseLong(req.getParameter("jobId"));
        
        Job job = jobService.getById(id);
        
        session.setAttribute("job", job);
        List<DepartmentType> departs = depService.getAll();
        session.setAttribute("departs", departs);
        String address = "./updateJob.jsp";

        RequestDispatcher dispatcher = req.getRequestDispatcher(address);

        dispatcher.forward(req, resp);

    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        HttpSession session = req.getSession();
     
        
        Job job=null;
        try{
        Long id = Long.parseLong(req.getParameter("jobId"));
         job = jobService.getById(id);
        } catch(ServiceException e) {
        	
        }
        
        boolean globalOk = true;
		boolean ok = false;
    	 String name ="";
    	 String nameMessage="";
         String requirements="";  
         String requirementsMessage="";
         String responsibilities="";
         String responsibilitiesMessage="";
    	
    	 
    	try {
    		name =  req.getParameter("name");
			ok = Validator.validateJobName(name);
			job.setName(name);
			if (ok == false) {
				nameMessage = "Please enter a real name!<br>(minim 3 alphabetical characters)";
				globalOk = false;
			}	
		} catch (Exception e) {
			nameMessage = "Please enter a real name!<br>(minim 3 alphabetical characters)";
			globalOk = false;
		}
    	
    	
    	 
    	try {
    		requirements =  req.getParameter("prereq");
			ok = Validator.validateText(requirements);
			job.setRequirements(requirements);
			if (ok == false) {
				requirementsMessage = "Please enter a requirement";
				globalOk = false;
			}	
		} catch (Exception e) {
			requirementsMessage = "Please enter a requirement";
			globalOk = false;
		}
    	
    	 
    	try {
    		responsibilities =  req.getParameter("resp");
			ok = Validator.validateText(responsibilities);
			job.setResponsibilities(responsibilities);
			if (ok == false) {
				responsibilitiesMessage = "Please enter a responsability";
				globalOk = false;
			}	
		} catch (Exception e) {
			responsibilitiesMessage = "Please enter a responsability";
			globalOk = false;
		}
    	 
    	 
    	try {
           
            int nrOfPositions = Integer.parseInt(req.getParameter("number"));
            String depart = req.getParameter("dept");
            DepartmentType department = depService.getByName(depart);
            String project = req.getParameter("proiect");
           job.setNrOfPositions(nrOfPositions);
           job.setDepartment(department);
           job.setProject(project);
            
        } catch (ServiceException | NumberFormatException ex) {
            

        	req.getSession().setAttribute("er", "There was a problem, please try again");
        
        	globalOk = false;}
            
          /*  
            
            String address = "./addJob.jsp";
            RequestDispatcher dispatcher = req.getRequestDispatcher(address);

            dispatcher.forward(req, resp);
        
            
            
        req.getSession().setAttribute("er", "Job added susseccfully");
        String address = "./showJobs.jsp";

        RequestDispatcher dispatcher = req.getRequestDispatcher(address);

        dispatcher.forward(req, resp);
        */
 

		if (globalOk == false) {
			
				
				System.out.println("cucc1");
                                session.setAttribute("jobId", job.getId());
				session.setAttribute("requirementsMessage", requirementsMessage);
				session.setAttribute("nameMessage", nameMessage);
				session.setAttribute("responsibilitiesMessage", responsibilitiesMessage);
				session.setAttribute("job", job);
				session.setAttribute("er", "There was a problem, please try again");
				String address2 = "./updateJob.jsp";
				RequestDispatcher dispatcher = req
						.getRequestDispatcher(address2);
				dispatcher.forward(req, resp);
			} 
			else {
			
				try{
					jobService.update(job);
				}
				catch(ServiceException e){
					System.out.println("cucc2");
					session.setAttribute("er", "Somthing went wrong with the server");
					String address2 = "./showJobs.jsp";
					RequestDispatcher dispatcher = req.getRequestDispatcher(address2);
					dispatcher.forward(req, resp);
					
				}
				
				List<User> involvedUsers = job.getInvolvedUsers();
		        
		        for(User involvedUser: involvedUsers) {
		        	Notification notif = new Notification();
		        	System.out.println("Adding a notification");
		        	notif.setDate(new Date());
		            notif.setNotification("Pozitia " + job.getName() + "a fost modificata.");
		            notif.setSeen(false);
		            notif.setUser(involvedUser);
		        	involvedUser.setNotification(notif);
		        	  userService.update(involvedUser);
		        }
		      

				
			session.setAttribute("er", "Job updated");
			List<Job> jobs=jobService.getAll();
			session.setAttribute("jobs", jobs);
			System.out.println("cucc3");
			String address2 = "./showJobs.jsp";
			RequestDispatcher dispatcher = req.getRequestDispatcher(address2);
			dispatcher.forward(req, resp);
		}
        
    }
    
}
